import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter) // 注册模块，已经是全局组件

// 下面这段代码作用：防止点击重复路由报错
const originalPush=VueRouter.prototype.push
VueRouter.prototype.push=function push(location){
	return originalPush.call(this,location).catch(err=>err)
}

const routes = [
  // {
  //   path: '/',
  //   name: 'Home',
  //   component: Home
  // },
  {
    path: '/login',
    name: 'Login',
    meta: {
      tabBarHide: true
    },
    component: () => import('../views/Login')
    // component: () => resolve => require(['@/views/Login'], resolve)
  },
  {
    path: '/films',
    name: 'films',
    redirect: '/films/nowplaying',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/films/Films.vue'),
    // 嵌套路由
    children: [
      {
        path: 'nowplaying',
        name: 'nowplaying',
        component: () => import(/* webpackChunkName: "Films" */ '../views/films/NowPlaying')
      },
      {
        path: 'comingsoon',
        name: 'comingsoon',
        component: () => import(/* webpackChunkName: "Films" */ '../views/films/ComingSoon')
      }
    ]
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    meta: {
      tabBarHide: true
    },
    component: () => import('../views/detail/Detail')
    // component: (resolve) => require(['@/views/components/Detail'], resolve)
  },
  {
    path: '/city',
    name: 'City',
    meta: {
      tabBarHide: true
    },
    component: () => import('../views/City')
  },
  {
    path: '/cinemas',
    name: 'Cinemas',
    component: () => import('../views/cinemas/Cinemas')
  },
  {
    path: '/cinemas/search',
    name: 'Search',
    meta: {
      tabBarHide: true
    },
    component: () => import('../views/cinemas/Search')
  },
  {
    path: '/news',
    name: 'News',
    component: () => import('../views/News')
  },
  {
    path: '/center',
    name: 'Center',
    meta: {
      requiresAuth: false
    },
    component: () => import('../views/center/Center')
  },
  {
    path: '*', // 通配符
    redirect: '/films'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes
})

router.beforeEach((to, from, next)=> {
  // 路由元信息
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if(!localStorage.getItem('token')) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router
